package com.jihe.ehmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihe.common.utils.PageUtils;
import com.jihe.common.utils.Query;
import com.jihe.ehmall.product.dao.CategoryBrandRelationDao;
import com.jihe.ehmall.product.entity.BrandEntity;
import com.jihe.ehmall.product.entity.CategoryBrandRelationEntity;
import com.jihe.ehmall.product.entity.CategoryEntity;
import com.jihe.ehmall.product.service.BrandService;
import com.jihe.ehmall.product.service.CategoryBrandRelationService;
import com.jihe.ehmall.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateBrandNameByBrandId(Long brandId, String name) {
        UpdateWrapper<CategoryBrandRelationEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("brand_name" , name);
        updateWrapper.eq("brand_id" , brandId);
        this.update(new CategoryBrandRelationEntity() , updateWrapper);
    }

    @Override
    @Transactional
    public void saveCategoryBrand(CategoryBrandRelationEntity categoryBrandRelation) {
        BrandEntity brandEntity = brandService.getById(categoryBrandRelation.getBrandId());
        CategoryEntity categoryEntity = categoryService.getById(categoryBrandRelation.getCatelogId());
        categoryBrandRelation.setBrandName(brandEntity.getName());
        categoryBrandRelation.setCatelogName(categoryEntity.getName());
        this.save(categoryBrandRelation);
    }

    @Override
    public List<CategoryBrandRelationEntity> queryCatelogListByBrandId(Long brandId) {
        QueryWrapper<CategoryBrandRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id" , brandId);
        List<CategoryBrandRelationEntity> entities = this.baseMapper.selectList(queryWrapper);
        return entities;
    }

}